package top.lshaci.learning.hutool;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.google.zxing.WriterException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

public class PdfToImageConverter {
    public static void main(String[] args) {
        try (PDDocument document = PDDocument.load(new File("D:\\pdf_test\\SettleBill40.pdf"))) {
            // 添加二维码到PDF
            addQRCodeToPDF(document, "单位: 西部物联; 单据号: WJ2502060001", 0, 0, 100);

            // 保存修改后的PDF
            document.save("D:\\pdf_test\\SettleBill40_with_qr.pdf");
            System.out.println("PDF添加二维码完成！");
        } catch (IOException | WriterException e) {
            System.err.println("PDF添加二维码时出错: " + e.getMessage());
        }
    }

    private static void addQRCodeToPDF(PDDocument document, String qrCodeData, float x, float y, int size) throws IOException, WriterException {
        // 将二维码转换为BufferedImage
        BufferedImage qrCodeImage = QrCodeUtil.generate(qrCodeData, size, size);

        // 将BufferedImage转换为PDImageXObject
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        javax.imageio.ImageIO.write(qrCodeImage, "png", baos);
        PDImageXObject pdImage = PDImageXObject.createFromByteArray(document, baos.toByteArray(), "QRCode.png");

        int numberOfPages = document.getNumberOfPages();
        System.err.println("页数：" + numberOfPages);
        // 获取PDF的第一页
        PDPage page = document.getPage(0);

        PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true);
        System.err.println("高度：" + page.getMediaBox().getHeight());
        // 在PDF页面上绘制二维码
        contentStream.drawImage(pdImage, x, page.getMediaBox().getHeight() - size, size, size);
        contentStream.close();
    }
}
   